//------------------------------------------------------------------------------
// <copyright file="DotBeerUpdatesInfoProvider.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAnton.Blocks.Updater;
using System.Xml;
using System.Configuration;
using System.Reflection;
using System.IO;
using System.Net.Sockets;
using System.Xml.Schema;
using DotBeer.Data;
using System.Diagnostics;

namespace DotBeer.Business.Entities.Updates
{
    public class DotBeerUpdatesInfoProvider : IUpdatesInfoProvider
    {
        #region public methods

        #region IUpdateInfoProvider Members

        public UpdateInfo GetUpdateInfo()
        {
            Configuration conf = ConfigurationManager.OpenExeConfiguration("DotBeer.Business.Entities.dll");

            if (!conf.HasFile)
                throw new FileNotFoundException("DotBeer.Business.Entities.dll not found");

            string downloadUrl = "";
            string updaterHash = "";
            Version latestVersion = null;

            XmlReader reader = null;

            try
            {
                string url = conf.AppSettings.Settings["updateUrl"].Value;
                string elementName = "";

                Assembly assm = Assembly.Load("DotBeer.Data");
                Stream schemaStream = assm.GetManifestResourceStream("DotBeer.Data.Schemas.UpdateInfoSchema.xsd");
                XmlSchema schema = XmlSchema.Read(schemaStream, null);
                schemaStream.Close();

                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ValidationType = ValidationType.Schema;
                settings.Schemas.Add(schema);
                settings.ValidationEventHandler += ((ob, args) =>
                    {
                        throw args.Exception;
                    });

                reader = XmlReader.Create(url, settings);
                reader.MoveToContent();

                if (reader.NodeType == XmlNodeType.Element &&
                    reader.Name == "app")
                {
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                            elementName = reader.Name;
                        else
                        {
                            if (reader.NodeType == XmlNodeType.Text &&
                                reader.HasValue)
                            {
                                switch (elementName)
                                {
                                    case "version":
                                        latestVersion = new Version(reader.Value);
                                        break;
                                    case "url":
                                        downloadUrl = reader.Value;
                                        break;
                                    case "sha256":
                                        updaterHash = reader.Value;
                                        break;
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }

            if (!downloadUrl.Contains("?name="))
                downloadUrl += String.Format("?name=DotBeer");

            downloadUrl += String.Format("&currentProgramVersion={0}",
                                          Assembly.GetExecutingAssembly().GetName().Version.ToString());

            return new UpdateInfo(downloadUrl, updaterHash, latestVersion);
        }

        #endregion

        #endregion
    }
}
